package com.eightywork.life.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.eightywork.life.R;
import com.eightywork.life.activity.LoginActivity.SinaLoginTask;
import com.eightywork.life.activity.LoginActivity.TencentLoginTask;
import com.eightywork.life.service.CacheService;
import com.eightywork.life.service.CpService;
import com.eightywork.life.service.DataService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.service.SpaceService;
import com.eightywork.life.util.MyHttpException;
import com.umeng.analytics.MobclickAgent;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

public class RegFirstActivity extends BaseActivity implements OnClickListener, Callback {
	private EditText account;
	private ImageButton returnButton;
	private Button loginButton, regButton, sina, tencent;
	private String username;
	private AsyncTask task;
	private boolean isLoading;
	public static RegFirstActivity activity = null;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_reg1);
		initView();
		activity = this;
		ShareSDK.initSDK(context);
	}

	@Override
	public void onResume() {		
		super.onResume();
		JPushInterface.onResume(this);
	    MobclickAgent.onResume(this);
	}
	
	@Override
	public void onPause() {
	    super.onPause();
		JPushInterface.onPause(this);
	    MobclickAgent.onPause(this);
	}


	public void initView() {
		account = (EditText) findViewById(R.id.account);
		returnButton = (ImageButton) findViewById(R.id.button_left);
		loginButton = (Button) findViewById(R.id.button_right);
		regButton = (Button) findViewById(R.id.get_val_button);
		sina = (Button) findViewById(R.id.sina);
		sina.setOnClickListener(this);		
		tencent = (Button) findViewById(R.id.tencent);
		tencent.setOnClickListener(this);
		returnButton.setOnClickListener(this);
		regButton.setOnClickListener(this);
		loginButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == returnButton) {
			hideKeyBoard(activity);
			finish();
		} else if (v == regButton) {
			reg();
		} else if (v == loginButton) {
			hideKeyBoard(activity);
			Intent intent = new Intent(this, LoginActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
//		} else if (v == sina) {
//			Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
//			if (!weibo.isValid()) {
//				weibo.setPlatformActionListener(new PaListener());
//				weibo.authorize();
//			} else {
//				showMessage("已经授权新浪微博");
//			}
//		} else if (v == tencent) {
//			Platform weibo = ShareSDK.getPlatform(context, TencentWeibo.NAME);
//			if (!weibo.isValid()) {
//				weibo.setPlatformActionListener(new PaListener());
//				weibo.authorize();
//			} else {
//				showMessage("已经授权腾讯微博");
//			}
//		}
		} else if (v == sina) {
			System.out.println("sina");
			final Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
			if (!weibo.isValid()) {
				weibo.setPlatformActionListener(new PlatformActionListener() {

					public void onComplete(Platform plat, int action,
							HashMap<String, Object> res) {
						Message msg = new Message();
						msg.arg1 = 1;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}

					public void onError(Platform plat, int action, Throwable t) {
						t.printStackTrace();

						Message msg = new Message();
						msg.arg1 = 4;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}
					
					public void onCancel(Platform plat, int action) {
						Message msg = new Message();
						msg.arg1 = 3;
						msg.arg2 = action;
						msg.obj = plat;
						weibo.removeAccount();
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}
				});
				weibo.authorize();
			} else {
				task = new SinaLoginTask().execute();
			}
		} else if (v == tencent) {
		//	System.out.println("tencent");
			final Platform weibo = ShareSDK.getPlatform(context, TencentWeibo.NAME);
			if (!weibo.isValid()) {
				weibo.setPlatformActionListener(new PlatformActionListener() {

					public void onComplete(Platform plat, int action,
							HashMap<String, Object> res) {
						Message msg = new Message();
						msg.arg1 = 2;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}

					public void onError(Platform plat, int action, Throwable t) {
						t.printStackTrace();
					    weibo.removeAccount();
						Message msg = new Message();
						msg.arg1 = 4;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}
					
					public void onCancel(Platform plat, int action) {
						Message msg = new Message();
						msg.arg1 = 3;
						msg.arg2 = action;
						msg.obj = plat;
						UIHandler.sendMessage(msg, RegFirstActivity.this);
					}
				});
				weibo.authorize();
			} else {
				task = new TencentLoginTask().execute();
						}
		}
	}
	
	class SinaLoginTask extends AsyncTask<Void, String, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("登录中...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
				PlatformDb db = weibo.getDb();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				CacheService.save(DoService.loginByWeibo(db.get("nickname"),
						db.getUserId(), db.getToken(), sdf.format(new Date(db.getExpiresTime())),
						""));
				CacheService.saveProfile(CpService.profile());
				DataService.setStruMap(DoService.xiaoquStru());
				DataService.setGroupList(SpaceService.group());
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				Intent intent = new Intent(context, IndexActivity.class);
				intent.putExtra("beginToload", true);
				startActivity(intent);
				LoginMapActivity.activity.finish();
				RegFirstActivity.this.finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

	class TencentLoginTask extends AsyncTask<Void, String, String> {

		@Override
		protected void onPreExecute() {
			showProgressDialog("登录中...");
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Platform weibo = ShareSDK.getPlatform(context,
						TencentWeibo.NAME);
				PlatformDb db = weibo.getDb();
				CacheService.save(DoService.loginByQQ(db.get("nickname"),
						db.getUserId(), db.getToken(), ""));
				CacheService.saveProfile(CpService.profile());
				DataService.setStruMap(DoService.xiaoquStru());
				DataService.setGroupList(SpaceService.group());
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			hideProgressDialog();
			if (result == null) {
				Intent intent = new Intent(context, IndexActivity.class);
				intent.putExtra("beginToload", true);
				startActivity(intent);
				LoginMapActivity.activity.finish();
				RegFirstActivity.this.finish();
			} else {
				showMessage(result);
			}
			super.onPostExecute(result);
		}
	}

//	class PaListener implements PlatformActionListener {
//		@Override
//		public void onCancel(Platform arg0, int arg1) {
//			showMessage("授权取消");
//		}
//
//		@Override
//		public void onComplete(Platform arg0, int arg1,
//				HashMap<String, Object> arg2) {
//			showMessage("授权成功");
//		}
//
//		@Override
//		public void onError(Platform arg0, int arg1, Throwable arg2) {
//			showMessage("授权错误" + arg2.getMessage());
//		}
//	}

	private void reg() {
		if (!isLoading) {
			isLoading = true;
			username = account.getEditableText().toString();
			if(username.length() != 11) {
				account.setText("");
				account.setError(Html.fromHtml("<font color=red>请输入号码正确位数!</font>"));
				isLoading = false;
				return ;
			}
			
			task = new RegTask().execute();
		}
	}

	class RegTask extends AsyncTask<Void, String, String> {
		JSONObject json;

		@Override
		protected String doInBackground(Void... params) {
			try {
				json = DoService.getSeccode(username);
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			
			if (json.optInt("error") == 1) {
				showAlert("提示", json.optString("msg"),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								JSONObject data = json.optJSONObject("data");
								if (data != null) {
									if (data.optString("success").equals("0")) {
										Intent intent = new Intent(context,
												RegSecondActivity.class);
										intent.putExtra("account", username);
										startActivity(intent);
									}
								}
							}
						});
			} else {
				JSONObject data = json.optJSONObject("data");
				System.out.println("---------验证码----" + data.optString("seccode"));
				showAlert("申请成功", "您的注册验证码已经通过短信发送至您的手机中，请在5分钟内完成注册，否则失效！",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent(context,
										RegSecondActivity.class);
								intent.putExtra("account", username);
								startActivity(intent);
							}
						});
			}
			isLoading = false;
			super.onPostExecute(result);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		Platform plat = (Platform) msg.obj;
		String text =LoginActivity.actionToString(msg.arg2);
		switch (msg.arg1) {
			case 1: {
				// 成功
//				text = plat.getName() + " completed at " + text;
//				showMessage(text);
				task = new SinaLoginTask().execute();
			}
			break;			
			case 2: {
				// 成功
//				text = plat.getName() + " completed at " + text;
//				showMessage(text);
				task = new TencentLoginTask().execute();
			}
			break;		
			case 3: {
				// 取消
				text = plat.getName() + " canceled at " + text;
			//	Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
				showMessage(text);
				return false;
			}
			case 4: {
				// 失败
				text = plat.getName() + " caught error at " + text;
				showMessage(text);
				return false;
			}
		}

	
		return false;
	}
}
